package ubc.cs.cpsc210.sustainabilityapp;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.mapsforge.android.maps.ArrayItemizedOverlay;
import org.mapsforge.android.maps.ArrayWayOverlay;
import org.mapsforge.android.maps.GeoPoint;
import org.mapsforge.android.maps.MapActivity;
import org.mapsforge.android.maps.MapController;
import org.mapsforge.android.maps.MapView;
import org.mapsforge.android.maps.MapViewMode;
import org.mapsforge.android.maps.OverlayItem;
import org.mapsforge.android.maps.OverlayWay;

import ubc.cs.cpsc210.sustainabilityapp.model.Buildings;
import ubc.cs.cpsc210.sustainabilityapp.model.FoodService;
import ubc.cs.cpsc210.sustainabilityapp.model.FoodServiceLocations;
import ubc.cs.cpsc210.sustainabilityapp.model.LatLong;
import ubc.cs.cpsc210.sustainabilityapp.model.POIRegistry;
import ubc.cs.cpsc210.sustainabilityapp.model.PointOfInterest;
import ubc.cs.cpsc210.sustainabilityapp.model.SharedPreferencesKeyValueStore;
import ubc.cs.cpsc210.sustainabilityapp.model.TourState;
import ubc.cs.cpsc210.sustainabilityapp.webservices.RouteInfo;
import ubc.cs.cpsc210.sustainabilityapp.webservices.RoutingService;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


/**
 * Activity representing the Map tab in the UI.
 */
public class MapDisplayActivity extends MapActivity {
			
	private LocationManager locationManager;
	
	private LocationListener locationListener;
	
	// User's latitude
	
	private double userLat;
	
	// User's longitude 
	
	private double userLong;
	
	// Location object containing user's GPS coordinate 
	
	private Location currentLocation;

	// The colour to use for the tour around the walking points
	private static final int DARK_BLUE = Color.rgb(0x57, 0x81, 0xFC);
	
	// The colour to use to plot route from user position to nearest building
	private static final int GREEN = Color.rgb(0, 51, 0);
	
	// The color to use to plot route from user position to nearest food service
	private static final int YELLOW = Color.YELLOW;

	// A string to indicate log messages logged from an object of this class
	private final static String LOG_TAG = "MapDisplayActivity";

	// The center point will be the ICICS building
	private final static GeoPoint ICICS_GEOPOINT = new GeoPoint(49.260887,
			-123.24902);

	/**
	 * Overlay for POI markers.
	 */

	private ArrayItemizedOverlay buildingOverlay;
	/**
	 * Overlay for nearest food locations.
	 */
	private ArrayItemizedOverlay foodOverlay;
	
	/**
	 * Overlay for user's position
	 */
	
	private ArrayItemizedOverlay userOverlay;
	
	/**
	 * Overlay for the route connecting the selected POI's.
	 */
	private ArrayWayOverlay tourOverlay;
	
	/**
	 * Overlay for the route connecting user's position and nearest building
	 */
	
	private ArrayWayOverlay nearestBuildingOverlay;
	
	/**
	 * Overlay for the route connecting user's position and nearest food service
	 */
	
	private ArrayWayOverlay nearestFoodOverlay;

	/**
	 * Manages and stores selected features and POI's.
	 */
	private TourState tourState;

	/**
	 * Currently selected POI's.
	 */
	private List<PointOfInterest> selectedPOIs;

	/**
	 * Wrapper for a service which calculates routes between POI's, and between
	 * the user's current location and the nearest selected POI.
	 */
	private RoutingService routingService;

	/**
	 * Easy access to all food service locations
	 */
	FoodServiceLocations foodServiceLocations;

	/**
	 * Currently selected restaurants.
	 */
	private List<FoodService> selectedFoodServiceLocations;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Initialize fields
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		locationListener = new createLocationListener();
		
		tourState = new TourState(POIRegistry.getDefault(),
				new SharedPreferencesKeyValueStore(this, TourState.STORE_NAME),
				new Buildings(POIRegistry.getDefault()));

		foodServiceLocations = new FoodServiceLocations(
				POIRegistry.getDefault());
		selectedFoodServiceLocations = new ArrayList<FoodService>();

		routingService = new RoutingService();

		MapView mapView = new MapView(this); 
		
		// Request location updates
		
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

		// Maps are downloaded from the Mapnik server -- an internet connection
		// is required.
		mapView.setMapViewMode(MapViewMode.MAPNIK_TILE_DOWNLOAD);
		mapView.setClickable(true);
		mapView.setBuiltInZoomControls(true);

		MapController mapController = mapView.getController();

		// Center the map on ICICS.
		mapController.setCenter(ICICS_GEOPOINT);

		// With the Mapnik server, this zoom level results in a map which
		// encompasses most of
		// the UBC campus.
		mapController.setZoom(mapView.getMaxZoomLevel() - 4);

		buildingOverlay = createBuildingOverlay();
		foodOverlay = createFoodOverlay();
		tourOverlay = createTourOverlay();
		userOverlay = createUserOverlay();
		nearestBuildingOverlay = createNearestBuildingOverlay();
		nearestFoodOverlay = createNearestFoodOverlay();

		// Order matters: overlays added later are displayed on top of overlays
		// added earlier.
		mapView.getOverlays().add(tourOverlay);
		mapView.getOverlays().add(nearestBuildingOverlay);
		mapView.getOverlays().add(nearestFoodOverlay);
		mapView.getOverlays().add(buildingOverlay);
		mapView.getOverlays().add(foodOverlay);
		mapView.getOverlays().add(userOverlay);

		setContentView(mapView);

	}

	/**
	 * Receive and update user's position 
	 */

	private class createLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			
			if (location != null) {
				userLat = location.getLatitude();
				userLong = location.getLongitude();
				currentLocation = location;
			}
			
			updateNearestBuildingRoute();
			
			updateNearestFoodRoute();
			
			userOverlay.clear();
			plotUser(userOverlay);
			
		}

		@Override
		public void onProviderDisabled(String provider) {
			// do nothing
		}

		@Override
		public void onProviderEnabled(String provider) {
			// do nothing
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// do nothing
		}
		
	}

	@Override
	protected void onDestroy() {
		if (routingService != null) {
			routingService.shutdown();
		}
		super.onDestroy();
	}

	/**
	 * Update the overlays based on the selected POI's and the user's current
	 * location.
	 */
	@Override
	protected void onResume() {
		selectedPOIs = tourState.getSelectedBuildings();

		updateTour(selectedPOIs);
		
		plotUser(userOverlay);
		
		updateNearestBuildingRoute();
		
		updateNearestFoodRoute();

		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menubutton, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection

		switch (item.getItemId()) {
		case R.id.clearFood:
			clearFood();
			break;
			
		case R.id.allFood:
			allFood();
			break;

		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * Update the POI markers and the route connecting them.
	 */
	private void updateTour(List<PointOfInterest> pois) {
		List<LatLong> pointsOnTour = null;
		
		buildingOverlay.clear();
		if (pois != null) {
			for (PointOfInterest poi : pois) {
				plotBuilding(buildingOverlay, poi);
			}
		}

		tourOverlay.clear();
		if (pois != null && pois.size() > 1) {
			pointsOnTour = new ArrayList<LatLong>();
			for (PointOfInterest poi : pois) {
				pointsOnTour.add(poi.getLatLong());
			}
			// Make sure the route connects back to the starting point.
			pointsOnTour.add(pois.get(0).getLatLong());

			findRouteAndUpdateOverlay(tourOverlay, pointsOnTour, true);
		
		}
				
	}
	
	/**
	 * Update the route from the user's position to the nearest building
	 */
	
	private void updateNearestBuildingRoute() {
		if (selectedPOIs != null && !selectedPOIs.isEmpty() && currentLocation != null) {
			nearestBuildingOverlay.clear();
			List<LatLong> tempList = new LinkedList<LatLong>();
			tempList.add(new LatLong (userLat, userLong));
			tempList.add(findClosestPOI(currentLocation, selectedPOIs).getLatLong());
			findRouteAndUpdateOverlay(nearestBuildingOverlay, tempList, true);
		}
		else
			nearestBuildingOverlay.clear();
	}
	
	private void updateNearestFoodRoute() {
		if (selectedFoodServiceLocations != null && !selectedFoodServiceLocations.isEmpty() && currentLocation != null) {
			nearestFoodOverlay.clear();
			List<LatLong> tempList = new LinkedList<LatLong>();
			tempList.add(new LatLong (userLat, userLong));
			tempList.add(findClosestPOI(currentLocation, selectedFoodServiceLocations).getLatLong());
			findRouteAndUpdateOverlay(nearestFoodOverlay, tempList, true);
		}
		else
			nearestFoodOverlay.clear();
	}
	

	/**
	 * Plot a POI on the specified overlay.
	 */
	private void plotBuilding(ArrayItemizedOverlay overlay, PointOfInterest poi) {
		GeoPoint point = new GeoPoint(poi.getLatLong().getLatitude(), poi
				.getLatLong().getLongitude());
		OverlayItem overlayItem = new OverlayItem(point, poi.getDisplayName(),
				poi.getDescription());
		overlay.addItem(overlayItem);
	}

	/**
	 * Plot a POI on the specified overlay.
	 */
	private void plotFood(FoodService poi) {
		GeoPoint point = new GeoPoint(poi.getLatLong().getLatitude(), poi
				.getLatLong().getLongitude());
		
		OverlayItem overlayItem = new OverlayItem(point, poi.getDisplayName(),
				poi.getDescription());
			
		foodOverlay.addItem(overlayItem);
	}

	private void plotUser(ArrayItemizedOverlay overlay) {
		GeoPoint point = new GeoPoint(userLat, userLong);
		OverlayItem overlayItem = new OverlayItem (point, "User", "User's position");
		overlay.addItem(overlayItem);
	}

	private void clearFood() {
		foodOverlay.clear();
		nearestFoodOverlay.clear();
		selectedFoodServiceLocations.clear();
	}
	
	private void allFood() {
		foodOverlay.clear();
		nearestFoodOverlay.clear();
		selectedFoodServiceLocations = foodServiceLocations.getAllFoodServiceLocations();
		for (FoodService aFood : selectedFoodServiceLocations) {
			plotFood(aFood);
		}
		updateNearestFoodRoute();
	}

	/**
	 * Given a location and a list of POI's, find the POI closest to the
	 * specified location.
	 * 
	 * This is based on "line-of-sight" distance between points, using an
	 * approximation which works okay for short distances (surface of the earth
	 * is approximated by a plane).
	 */
	private PointOfInterest findClosestPOI(Location location,
			List<? extends PointOfInterest> pois) {
		double approxLatitude = pois.get(0).getLatLong().getLatitude();

		PointOfInterest closest = null;
		double minDistValue = Double.MAX_VALUE;

		LatLong locationLatLong = new LatLong(location.getLatitude(),
				location.getLongitude());

		for (PointOfInterest poi : pois) {
			double distValue = getDistanceValue(approxLatitude,
					locationLatLong, poi.getLatLong());
			if (distValue < minDistValue) {
				minDistValue = distValue;
				closest = poi;
			}
		}

		return closest;
	}

	/**
	 * Get a value representing the "line-of-sight" distance between two points,
	 * using an approximation which works okay for short distances (surface of
	 * the earth is approximated by a plane).
	 * 
	 * The value returned is only usable for comparison purposes (i.e. it has a
	 * nonlinear relationship to the actual distance).
	 */
	private double getDistanceValue(double approxLatitude, LatLong pointA,
			LatLong pointB) {
		double latAdjust = Math.cos(Math.PI * approxLatitude / 180.0);
		double latDiff = pointA.getLatitude() - pointB.getLatitude();
		double longDiff = pointA.getLongitude() - pointB.getLongitude();

		return Math.pow(latDiff, 2) + Math.pow(latAdjust * longDiff, 2);
	}

	/**
	 * Create the overlay for POI markers.
	 */
	private ArrayItemizedOverlay createBuildingOverlay() {
		return new ArrayItemizedOverlay(getResources().getDrawable(
				R.drawable.map_pin_blue)) {
			@Override
			protected boolean onTap(int index) {
				final PointOfInterest poi = selectedPOIs.get(index);
				AlertDialog.Builder dialog = new AlertDialog.Builder(
						MapDisplayActivity.this);

				// button that displays three nearest food locations
				DialogInterface.OnClickListener showFood = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						
						foodOverlay.clear();
						selectedFoodServiceLocations = foodServiceLocations.getThreeClosestToLocation(poi.getLatLong());
						for (FoodService f : selectedFoodServiceLocations) {
							plotFood(f);
						}
						updateNearestFoodRoute();
						dialog.cancel();
						
					}
				};

				// button that cancels dialog
				DialogInterface.OnClickListener cancel = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				};
				
				
				dialog.setPositiveButton("Nearest Food", showFood);
				dialog.setNegativeButton("Cancel", cancel);

				dialog.setTitle(poi.getDisplayName());
				dialog.setMessage(poi.getDescription());
				dialog.show();
				return true;
			}
		};
	}

	/**
	 * Create the overlay for food service locations
	 */
	private ArrayItemizedOverlay createFoodOverlay() {  
		
		return new ArrayItemizedOverlay(getResources().getDrawable(R.drawable.marker10)) {
			@Override
			protected boolean onTap(int index) {
				
				// Tap should be impossible in this situation.
				if (selectedFoodServiceLocations.isEmpty()) {
					return true;
				}

				final FoodService clicked = selectedFoodServiceLocations
						.get(index);
				final Dialog dialog = new Dialog(
						MapDisplayActivity.this);
				
				dialog.setContentView(R.layout.foodservicedialog);
				
				// set title of dialog to name of food service
				dialog.setTitle(clicked.getDisplayName());
				
				// set category image of food service
				ImageView foodimage = (ImageView) dialog.findViewById(R.id.foodimage);
				foodimage.setImageDrawable(getIcon(clicked.getCategory()));
				
				// set category name of food service 
				TextView category = (TextView) dialog.findViewById(R.id.category);
				category.setText(clicked.getCategory());
				
				// set number of reviews of food service
				TextView numberofratings = (TextView) dialog.findViewById(R.id.numberofratings);
				if (clicked.getReviewCount() <= 1) {
					numberofratings.setText("(" + clicked.getReviewCount() + " review)");
				}
				else {
					numberofratings.setText("(" + clicked.getReviewCount() + " reviews)");
				}
				
				// set rating image of food service 
				ImageView rating = (ImageView) dialog.findViewById(R.id.rating);
				rating.setImageDrawable(getRatingIcon(clicked.getRating()));
				
				// food dialog buttons
				
				Button url = (Button) dialog.findViewById(R.id.url);
				/*Button yelp = (Button) dialog.findViewById(R.id.yelp);*/
				Button cancel = (Button) dialog.findViewById(R.id.cancel);
				Button directions = (Button) dialog.findViewById(R.id.directions);
				
				// cancel button - clear dialog
				cancel.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.cancel();
					}
				});
				
				// url button - launch website for food service 
				url.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						String website = clicked.getUrl();
						Intent i = new Intent(Intent.ACTION_VIEW);
						i.setData(Uri.parse(website));
						startActivity(i);
					}
				});
				
			    // yelp button - launch website for yelp
		/*		yelp.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent i = new Intent(Intent.ACTION_VIEW);
						i.setData(Uri.parse("http://m.yelp.ca/"));
						startActivity(i);
					}
				});*/
				
				// directions button - plot route from user to clicked food service
				directions.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						foodOverlay.clear();
						selectedFoodServiceLocations.clear();
						selectedFoodServiceLocations.add(clicked);
						updateNearestFoodRoute();
						plotFood(clicked);
						dialog.cancel();
					}
				});
				
				dialog.show();

				return true;
			}
		};
	}

	/**
	 * Create the overlay for the route connecting the selected POI's.
	 */
	private ArrayWayOverlay createTourOverlay() {
		Paint wayOverlayFill = new Paint(Paint.ANTI_ALIAS_FLAG);
		wayOverlayFill.setStyle(Paint.Style.STROKE);
		wayOverlayFill.setColor(DARK_BLUE);
		wayOverlayFill.setStrokeWidth(4);

		return new ArrayWayOverlay(wayOverlayFill, null);
	}
	
	/**
	 * Create the overlay for the user's position
	 */
	
	private ArrayItemizedOverlay createUserOverlay() {
		return new ArrayItemizedOverlay(getResources().getDrawable(
				R.drawable.bulbgreyhalo)) {
			
			@Override
			protected boolean onTap(int index) {
				
				AlertDialog.Builder dialog = new AlertDialog.Builder(
						MapDisplayActivity.this);
				
				// button that displays three nearest food locations
				DialogInterface.OnClickListener showFood = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						
						foodOverlay.clear();
						selectedFoodServiceLocations = foodServiceLocations.getThreeClosestToLocation(new LatLong(userLat, userLong));
						for (FoodService f : selectedFoodServiceLocations) {
							plotFood(f);
						}
						updateNearestFoodRoute();
						dialog.cancel();
						
					}
				};
				
				// button that cancels dialog
				DialogInterface.OnClickListener cancel = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				};
				
				dialog.setPositiveButton("Nearest Food", showFood);
				dialog.setNegativeButton("Cancel", cancel);
				
				dialog.setTitle("Your Location");
				dialog.show();

				return true;
			}
		};
	}
	
	private ArrayWayOverlay createNearestBuildingOverlay() {
		Paint wayOverlayFill = new Paint(Paint.ANTI_ALIAS_FLAG);
		wayOverlayFill.setStyle(Paint.Style.STROKE);
		wayOverlayFill.setColor(GREEN);
		wayOverlayFill.setStrokeWidth(3);
		wayOverlayFill.setPathEffect(new DashPathEffect(new float[] {2, 3}, 0));

		return new ArrayWayOverlay(wayOverlayFill, null);
	}
	
	private ArrayWayOverlay createNearestFoodOverlay() {
		Paint wayOverlayFill = new Paint(Paint.ANTI_ALIAS_FLAG);
		wayOverlayFill.setStyle(Paint.Style.STROKE);
		wayOverlayFill.setColor(Color.RED);
		wayOverlayFill.setStrokeWidth(3);
		wayOverlayFill.setPathEffect(new DashPathEffect(new float[] {2, 3}, 0));

		return new ArrayWayOverlay(wayOverlayFill, null);
	}
		
	/**
	 * Calls the routing service to obtain a route which connects the specified
	 * list of lat/long points.
	 * 
	 * @param overlay
	 *            The way overlay which will be updated with the resulting
	 *            route.
	 * @param points
	 *            Points which the route must pass through.
	 * @param useCache
	 *            If set to true, the routing service will return a cached route
	 *            if one is available (and will cache the result if no cached
	 *            route is found).
	 */
	private void findRouteAndUpdateOverlay(ArrayWayOverlay overlay,
			List<LatLong> points, boolean useCache) {
		// Retrieve routes in a separate thread, as it can take some time and we
		// do not want to
		// block the UI thread.
		RouteRetriever retriever = new RouteRetriever(overlay, points, useCache);
		new Thread(retriever).start();
	}

	/**
	 * Add a route to the specified overlay.
	 */
	private void addRouteToOverlay(ArrayWayOverlay overlay,
			List<LatLong> waypoints) {
		List<GeoPoint> points = new ArrayList<GeoPoint>();
		for (LatLong latLong : waypoints) {
			points.add(new GeoPoint(latLong.getLatitude(), latLong
					.getLongitude()));
		}
		overlay.addWay(new OverlayWay(new GeoPoint[][] { points
				.toArray(new GeoPoint[] {}) }));
	}

	/**
	 * Calls the routing service to obtain a route which connects the specified
	 * list of lat/long points, and updates the overlay provided with the
	 * resulting route.
	 * 
	 * Routes are retrieved in a separate thread, as it can take some time and
	 * we do not want to block the UI thread.
	 */
	private class RouteRetriever implements Runnable {
		private ArrayWayOverlay overlay;
		private List<LatLong> points;
		private boolean useCache;

		public RouteRetriever(ArrayWayOverlay overlay, List<LatLong> points,
				boolean useCache) {
			this.overlay = overlay;
			this.points = points;
			this.useCache = useCache;
		}

		@Override
		public void run() {
			try {
				if (points.size() > 1) {
					for (int i = 1; i < points.size(); i++) {
						LatLong currPoint = points.get(i - 1);
						LatLong nextPoint = points.get(i);
						RouteInfo info = routingService.getRoute(currPoint,
								nextPoint, useCache);

						final List<LatLong> waypoints = new ArrayList<LatLong>();
						waypoints.add(currPoint);
						waypoints.addAll(info.getWaypoints());
						waypoints.add(nextPoint);

						// Updates to the UI must run on the UI thread.
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								addRouteToOverlay(overlay, waypoints);
							}

						});
					}
				}
			} catch (Exception e) {
				Log.e(LOG_TAG, "Error retrieving route from route service", e);
			}
		}
	}
	
	private Drawable getIcon(String category) {
		Drawable myIcon = null;
		if (category.contains("Cafes") 
				|| category.contains("Breakfast")
				|| category.contains("Bagels")
				|| category.contains("Creperies")
				|| category.contains("Sandwiches")){
			myIcon = getResources().getDrawable(R.drawable.food_cafe);
		} else 	if (category.contains("American") 
				|| category.contains("Burgers")
				|| category.contains("Hot Dogs")){
			myIcon = getResources().getDrawable(R.drawable.food_amer);
		} else 	if (category.contains("Pubs")){
			myIcon = getResources().getDrawable(R.drawable.food_pubs);
		} else 	if (category.contains("Chinese") 
				|| category.contains("Korean")
				|| category.contains("Taiwanese")){
			myIcon = getResources().getDrawable(R.drawable.food_chn);
		} else 	if (category.contains("Japanese") 
				|| category.contains("Sushi")){
			myIcon = getResources().getDrawable(R.drawable.food_jap);
		} else 	if (category.contains("Vegetarian")){
			myIcon = getResources().getDrawable(R.drawable.food_veg);
		} else 	if (category.contains("Pizza")){
			myIcon = getResources().getDrawable(R.drawable.food_pizza);
		} else 	if (category.contains("Mexican") 
				|| category.contains("Indian")
				|| category.contains("Pakistani")
				|| category.contains("Greek")
				|| category.contains("Mediterranean")){
			myIcon = getResources().getDrawable(R.drawable.food_spicy);
		} else myIcon = getResources().getDrawable(R.drawable.food_other);
		return myIcon;
	}

	private Drawable getRatingIcon(Double rating) {
		if (rating >= 0 && rating < 1) {
			return getResources().getDrawable(R.drawable.stars_0);
		}
		else if (rating >= 1 && rating < 1.5) {
			return getResources().getDrawable(R.drawable.stars_1);
		}
		else if (rating >= 1.5 && rating < 2) {
			return getResources().getDrawable(R.drawable.stars_1_half);
		}
		else if (rating >= 2 && rating < 2.5) {
			return getResources().getDrawable(R.drawable.stars_2);
		}
		else if (rating >= 2.5 && rating < 3) {
			return getResources().getDrawable(R.drawable.stars_2_half);
		}
		else if (rating >= 3 && rating < 3.5) {
			return getResources().getDrawable(R.drawable.stars_3);
		}
		else if (rating >= 3.5 && rating < 4) {
			return getResources().getDrawable(R.drawable.stars_3_half);
		}
		else if (rating >= 4 && rating < 4.5) {
			return getResources().getDrawable(R.drawable.stars_4);
		}
		else if (rating >= 4.5 && rating < 5) {
			return getResources().getDrawable(R.drawable.stars_4_half);
		}
		else if (rating >= 5) {
			return getResources().getDrawable(R.drawable.stars_5);
		}
		return null;
	}

}
